package com.pyq;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.adpter.GridViewAdapter;
import com.android.ocean.util.common.StringUtil;
import com.app.DemoApplication;
import com.contact.BaseActivity;
import com.easemob.chatuidemo.utils.CommonUtils;
import com.easemob.util.PathUtil;
import com.http.PublishToPyqTask;
import com.http.PublishToPyqTask.CallBack;
import com.http.UploadFileTask;
import com.matang.R;
import com.util.AppUtil;
import com.util.ImageHelper;
import com.view.NonScrollGridView;

public class SlectResultActivity extends BaseActivity implements UploadFileTask.CallBack{
	private GridViewAdapter adapter;
	private NonScrollGridView gridView;
	private List<String> maps = new ArrayList<String>();
	private TextView tvFb;
	private EditText edContent;
	private StringBuffer sb = new StringBuffer();
	private static final int SELECT_PIC_BY_TAKE_PHOTO = 11;
	private File cameraFile;
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.result_main);
		File flFile = new File(localTempImgDir);
		if (!flFile.exists()) {
			flFile.mkdir();
		}



		maps.clear();
		init();
	}

	private void init() {
		findView();
		setData();

	}

	/**
	 * 调用系统照相功能，照相文件指向imageUri路径 .
	 */
	private int tag;
	private String localTempImgDir = Environment
			.getExternalStorageDirectory() + "/mytup";
	private String localTempImgFileName;
	private File f;

	private void showImg() {

		new AlertDialog.Builder(this).setTitle("选择")
		.setPositiveButton("相册", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				tag = 0;
				Intent intent = new Intent();
				/* 开启Pictures画面Type设定为image */
				intent.setType("image/*");
				/* 使用Intent.ACTION_GET_CONTENT这个Action */
				intent.setAction(Intent.ACTION_GET_CONTENT);
				/* 取得相片后返回本画面 */
				startActivityForResult(intent, 1);



			}
		}).setNegativeButton("相机", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {

				tag = 1;
				//				localTempImgDir = Environment
				//						.getExternalStorageDirectory() + "/mytup";
				//
				//				File flFile = new File(localTempImgDir);
				//				flFile.mkdir();
				//				localTempImgFileName = DateFormat.format(
				//						"yyyyMMdd_hhmmss",
				//						Calendar.getInstance(Locale.CHINA))
				//						+ ".jpg";
				//				Intent intent = new Intent(
				//						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				//				f = new File(localTempImgDir, localTempImgFileName);// localTempImgDir和localTempImageFileName是自己定义的名字
				//
				//				Uri u = Uri.fromFile(f);
				//				intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
				//				intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
				//
				//				startActivityForResult(intent, 2);

				if (!CommonUtils.isExitsSdcard()) {
					Toast.makeText(getApplicationContext(), "SD卡不存在，不能拍照", 0).show();
					return;
				}

				cameraFile = new File(PathUtil.getInstance().getImagePath(), DemoApplication.getInstance().getUserName()
						+ DateFormat.format("yyyyMMdd_hhmmss",
								Calendar.getInstance(Locale.CHINA)) + ".jpg");
				cameraFile.getParentFile().mkdirs();
				startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
						SELECT_PIC_BY_TAKE_PHOTO);

				/*
				 * //拍照我们用Action为MediaStore.ACTION_IMAGE_CAPTURE，
				 * //有些人使用其他的Action但我发现在有些机子中会出问题，所以优先选择这个 Intent intent
				 * = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				 * intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
				 * startActivityForResult(intent, code);
				 */
			}
		}).show();

	}


	private void setData() {
		if (adapter == null) {
			adapter = new GridViewAdapter(this);
		}
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {


			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				if (position == gridView.getAdapter().getCount() - 1) { 
					showImg();
				}else {

				}


			}
		});

	}
	private ImageView imgBack;
	private String attachments = "";
	private void findView() {
		imgBack = (ImageView) findViewById(R.id.img_back);
		edContent = (EditText) findViewById(R.id.ed_content);
		tvFb = (TextView) findViewById(R.id.tv_fb);
		gridView = (NonScrollGridView) findViewById(R.id.grid_img_room);
		findViews();
		initPaneData();
		imgBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				SlectResultActivity.this.finish();

			}
		});
		tvFb.setOnClickListener(new OnClickListener() {


			public void onClick(View view) {
				String content = edContent.getText().toString();
				sendDataToServer(content, attachments);
			}
		});

	}
	public void initPaneData() {


		header.headTitleTv.setVisibility(View.VISIBLE);
		header.headTitleTv.setText("发布朋友圈");
		header.headLeftTv.setVisibility(View.VISIBLE);
		header.headRightTv.setVisibility(View.GONE);
		header.headLeftTv.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				SlectResultActivity.this.finish();

			}
		});
	}

	public String getRealPathFromURI(Uri contentUri) {
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(contentUri, proj, null, null, null);
		int column_index
		= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	} 
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		String testPath = null;
		if (tag == 1) {//相机
			if (cameraFile != null && cameraFile.exists()){
				
				testPath= cameraFile.getAbsolutePath();
				Log.i("test", "朋友圈上传的图片路径=="+testPath);
			}else {
				Toast.makeText(getApplicationContext(), "获取图片失败，建议从相册选择", 1).show();
			}


		}else if(tag == 0){
			if (data != null) {
				Uri uri = data.getData();
				testPath = getRealPathFromURI(uri);
			}

		}
		if (testPath != null) {
			maps.clear();
			maps.add(testPath);
			adapter.getImgPaths().remove("add");

			adapter.addDatas(maps);
			adapter.getImgPaths().add("add");
		}

		if (testPath != null) {
			Bitmap ysBitmap;
			Bitmap bitmap;
			ysBitmap = ImageHelper.createNewBitmapAndCompressByFile(
					testPath, new int[] { 640, 480 });
			bitmap = ImageHelper.comp(ysBitmap);
			File newfile = new File(localTempImgDir + "/"
					+ System.currentTimeMillis() + ".jpg");
			boolean sucess = ImageHelper.saveCompressBitmap(bitmap,
					newfile);


			//	File newFile = new File(testPath);
			if (sucess) {
				String name = newfile.getName();
				String ss = newfile.getAbsolutePath();
				String path =ss.substring(0,ss.lastIndexOf("/"))+"/";
				uploadVoice(path, name);
			}


		}


	}

	/**
	 * @param path  //路径
	 * @param name //名字
	 */
	private void uploadVoice(String path, String name) {
		showProgressDialog("图片上传中…………");
		new UploadFileTask(this).execute(path, name);
	}


	public void procError(String msg) {

	}

	//上传文件成功
	private void sendDataToServer(String content, String attachments) {
		if (StringUtil.isNull(content)) {
			AppUtil.tsMsg(getApplicationContext(), "内容不能为空");
		} else {
			showProgressDialog("发送中...");
			//domassage
			//			String uid = "";
			//			User user = UserUtil.readUser();
			//			if (user != null) {
			//				uid = user.id;
			//			}

			attachments = sb.toString();
			HashMap<String, Object> map = new HashMap<String, Object>();
			//map.put("id",uid);
			map.put("content", content);
			map.put("attachments", attachments);

			new PublishToPyqTask(callback).execute(map);

		}

	}
	//发布到朋友圈后
	CallBack callback = new CallBack() {


		public void procError(String msg) {
			//

		}

		@Override
		public void procFbToPyq(String result) {
			dismissProgressDialog();
			AppUtil.tsMsg(getApplicationContext(), "发布到朋友圈成功");
			DemoApplication.getInstance().getHandler().sendEmptyMessage(1);
			SlectResultActivity.this.finish();

			//AppUtil.tsMsg(getApplicationContext(), result);

		}
	};

	public void procUploadFile(String result) {
		dismissProgressDialog();
		try {
			JSONObject jo = new JSONObject(result);
			String severPath = jo.getString("src");
			sb.append(severPath+",");
			//	sendDataToServer(jo.getString("src"), "voice");
		} catch (JSONException e) {
			e.printStackTrace();
		}


	}

	@Override
	public void procUploadFileError(String result) {
		dismissProgressDialog();
		AppUtil.tsMsg(getApplicationContext(), "图片上传失败");
		if (adapter.getCount() >0 ) {
			adapter.getImgPaths().remove(adapter.getCount()-1);
			adapter.notifyDataSetChanged();
		}


	}





}
